package seg.tef4.whms.component;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.scan.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.List;

import okhttp3.ResponseBody;
import params.com.stepview.StatusViewScroller;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import seg.tef4.whms.activity.ReturnRequestApprovalActivity;
import seg.tef4.whms.apis.OutWarehouseApi;
import seg.tef4.whms.apis.ReturnWarehouseApi;
import seg.tef4.whms.domain.TOutWarehouse;
import seg.tef4.whms.domain.TSparePart;
import seg.tef4.whms.domain.entity.SysUser;
import seg.tef4.whms.util.auth.OnlineUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;
import seg.tef4.whms.util.retrofitutil.RetrofitUtil;

public class ReturnRequestApprovalView {

    private static ReturnWarehouseApi returnWarehouseApi = (ReturnWarehouseApi)  RetrofitUtil.getApiInstance(ReturnWarehouseApi.class);


    /** 组件持有者，继承了ViewHolder在构造函数中通过传入的view对其组件内容进行赋值缓存 **/
    private static class RecycleHolder extends RecyclerView.ViewHolder {

        private TextView materialNo;
        private TextView line;
        private TextView station;

        private TextView outNum;
        private TextView outType;

        private TextView createBy;
        private TextView status;

        private TextView name;
        private TextView brand;

        private TextView location;
        private TextView specification;

        private TextView createTimeStr;

        private Button button;

        private RecycleHolder(View itemView) {
            super(itemView);
            materialNo = itemView.findViewById(R.id.out_warehouse_recycleView_materialNo);
            line = itemView.findViewById(R.id.out_warehouse_recycleView_line);
            station = itemView.findViewById(R.id.out_warehouse_recycleView_station);
            outNum = itemView.findViewById(R.id.out_warehouse_recycleView_outNum);
            outType = itemView.findViewById(R.id.out_warehouse_recycleView_outType);
            createBy = itemView.findViewById(R.id.out_warehouse_recycleView_createBy);
            status = itemView.findViewById(R.id.out_warehouse_recycleView_status);
            createTimeStr = itemView.findViewById(R.id.out_warehouse_recycleView_createTimeStr);
            name = itemView.findViewById(R.id.out_warehouse_recycleView_name);
            brand = itemView.findViewById(R.id.out_warehouse_recycleView_brand);
            location = itemView.findViewById(R.id.out_warehouse_recycleView_location);
            specification = itemView.findViewById(R.id.out_warehouse_recycleView_specification);
            button = itemView.findViewById(R.id.button);
        }
    }

    /** 适配器继承RecyclerView.Adapter，实例化时传入数据作为成员变量，必须实现三个函数。**/
    public static class RecycleViewAdapter extends RecyclerView.Adapter{

        ReturnRequestApprovalActivity context;
        List<TOutWarehouse> data;
        String type_zn;

        public RecycleViewAdapter(List<TOutWarehouse> data,String type_zn,ReturnRequestApprovalActivity context){
            this.data = data;
            this.type_zn = type_zn;
            this.context = context;
        }

        /**对layout资源进行加载获得view，将view传入组件持有者的构造函数获得其实例返回。主要工作是渲染页面并构造组件缓存*/
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.return_request_approval_recycleview_item,parent,false);
            RecycleHolder recycleHolder = new RecycleHolder(view);
            setItemClickListener(recycleHolder);
            return recycleHolder;
        }

        /**处理item滑入屏幕时的回调函数，通过item的数据，对组件持有者中的组件属性进行赋值。
         这里需要注意的是，由于函数重写方法形参类型不可改变，这里要使用子类的get方法时需要向下强转*/
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            TOutWarehouse item = data.get(position);
            RecycleHolder recycleHolder = (RecycleHolder) holder;
            recycleHolder.materialNo.setText(item.getMaterialNo());
            recycleHolder.line.setText(item.getLine());
            recycleHolder.station.setText(item.getStation());
            recycleHolder.outNum.setText(String.valueOf(item.getOutNum()));
            recycleHolder.outType.setText(item.getOutType());
            recycleHolder.createBy.setText(item.getSysUser().getNickName());
            recycleHolder.status.setText(item.getStatusStr());
            recycleHolder.createTimeStr.setText(item.getCreateTimeStr());
            recycleHolder.name.setText(item.gettSparePart().getName());
            recycleHolder.brand.setText(item.gettSparePart().getBrand());
            recycleHolder.location.setText(item.gettSparePart().getLocation());
            recycleHolder.specification.setText(item.gettSparePart().getSpecification());
            recycleHolder.button.setText(type_zn);

            recycleHolder.button.setOnClickListener(view -> {
                Long id = item.getId();
                if(type_zn.equals("退库申请")){
                    AlertDialogCreator.getQueryDialog(context, "系统询问",
                            "你确定要提出申请么？",
                            "确定", (dialogInterface, i) -> {return_request(id);},"取消",
                            null).show();
                }

                else if(type_zn.equals("一级审批")){
                    AlertDialogCreator.getQueryDialog(context, "系统询问", "你确定要审批么？",
                            "确定", (dialogInterface, i) -> {approval1(id);},"取消",
                            null).show();
                }

                else if(type_zn.equals("二级审批")) {
                    AlertDialogCreator.getQueryDialog(context, "系统询问", "你确定要审批么？",
                            "确定", (dialogInterface, i) -> {approval2(id);}, "取消",
                            null).show();
                }

            });
        }

        /** 申请退库 **/
        private void return_request(Long id){
            Long[] ids= {id};
            returnWarehouseApi.add(OnlineUser.getToken(context),ids).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resultJson = response.body().string();
                        JSONObject result = new JSONObject(resultJson);
                        int code = result.getInt("code");
                        String msg = result.getString("msg");
                        if (code == 200) {
                            context.queryOutWarehouse(true);
                            AlertDialogCreator.getConfirmDialog(context,
                                    "系统提示", msg, "确认", null).show();
                        } else {
                            throw new RuntimeException(code + ":" + msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        AlertDialogCreator.getConfirmDialog(context,
                                "系统错误", e.toString(), "确认", null).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    AlertDialogCreator.getConfirmDialog(context,
                            "系统错误", t.toString(), "确认", null).show();
                }
            });
        }

        /** 一级审批 **/
        private void approval1(Long id){
            returnWarehouseApi.part_return_approval1(OnlineUser.getToken(context),id).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resultJson = response.body().string();
                        JSONObject result = new JSONObject(resultJson);
                        int code = result.getInt("code");
                        String msg = result.getString("msg");
                        if (code == 200) {
                            context.queryOutWarehouse(true);
                            AlertDialogCreator.getConfirmDialog(context,
                                    "系统提示", msg, "确认", null).show();
                        } else {
                            throw new RuntimeException(code + ":" + msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        AlertDialogCreator.getConfirmDialog(context,
                                "系统错误", e.toString(), "确认", null).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    AlertDialogCreator.getConfirmDialog(context,
                            "系统错误", t.toString(), "确认", null).show();
                }
            });
        }

        /** 二级审批 **/
        private void approval2(Long id){
            returnWarehouseApi.part_return_approval2(OnlineUser.getToken(context),id).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String resultJson = response.body().string();
                        JSONObject result = new JSONObject(resultJson);
                        int code = result.getInt("code");
                        String msg = result.getString("msg");
                        if (code == 200) {
                            context.queryOutWarehouse(true);
                            AlertDialogCreator.getConfirmDialog(context,
                                    "系统提示", msg, "确认", null).show();
                        } else {
                            throw new RuntimeException(code + ":" + msg);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        AlertDialogCreator.getConfirmDialog(context,
                                "系统错误", e.toString(), "确认", null).show();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    AlertDialogCreator.getConfirmDialog(context,
                            "系统错误", t.toString(), "确认", null).show();
                }
            });
        }

        // 获取项数，直接返回数据源的长度即可。这里将数据源在构造函数中传入作成员变量，有利于其他方法的数据共享。
        @Override
        public int getItemCount() {
            return data.size();
        }

        // 监听函数
        private void setItemClickListener(RecyclerView.ViewHolder holder){
            holder.itemView.setOnClickListener((view -> {
                int index = holder.getPosition();
                TOutWarehouse item = data.get(index);
                String info = new StringBuilder()
                        .append("物料号: ").append(item.getMaterialNo()).append("\n")
                        .append("名称: ").append(item.gettSparePart().getName()).append("\n")
                        .append("品牌: ").append(item.gettSparePart().getBrand()).append("\n")
                        .append("型号: ").append(item.gettSparePart().getSpecification()).append("\n")
                        .append("产线: ").append(item.getLine()).append("\n")
                        .append("工位: ").append(item.getStation()).append("\n")
                        .append("位置: ").append(item.gettSparePart().getLocation()).append("\n")
                        .append("出库数量: ").append(item.getOutNum()).append("\n")
                        .append("出库类型: ").append(item.getOutType()).append("\n")
                        .append("出库人: ").append(item.getSysUser().getNickName()).append("\n")
                        .append("状态: ").append(item.getStatusStr()).append("\n")
                        .append("出库时间: ").append(item.getCreateTimeStr()).append("\n").toString();
                AlertDialogCreator.getConfirmDialog(holder.itemView.getContext(),
                        "显示信息", info, "确认", null).show();

            }));
        }
    }
}

